var Product = {
    btp : baidu.template,
    TIME : '',
    flag : $('body').data('version') == "None" ? false : true,
    scrollTo : function (scrollTo, time) {
        var scrollFrom = parseInt(document.body.scrollTop, 10),
            i = 0,
            runEvery = 5; // run every 5ms

        scrollTo = parseInt(scrollTo, 10);
        time /= runEvery;

        var interval = setInterval(function () {
            i++;

            document.body.scrollTop = (scrollTo - scrollFrom) / time * i + scrollFrom;

            if (i >= time) {
                clearInterval(interval);
            }
        }, runEvery);
    },
    topSlider : function () {
        var slider = new Swiper('.swiper-container', {
            mode: 'horizontal',
            loop: true,
            autoplay: 3000,
            // pagination: '.swiper-pagination',
            onTouchStart: function(){
                setTimeout(function(){
                    slider.startAutoplay();
                }, 3000);
            }
        });
    },
    talentHeader : function(){
        var followBtn = $('#friendship');
        followBtn.length > 0 && followBtn.click(function(){
            var userid = followBtn.data('uid'),
                url = '/u/' + userid + '/friendship/follow/';
            $.post(url, {
                csrfmiddlewaretoken: $('body').data('csrf')
            }, function(data) {
                if ( data.sucess ) {
                    switch ( data.relationship ) {
                        case 2:
                            followBtn.find('b').text('已关注');
                            followBtn.find('span').addClass('icon-following');
                            followBtn.attr('href', followBtn.attr('data-jumptouser'));
                        break;
                    }
                }
            });
        });
    },
    talentVideo : function(){
        var video = $(".talent-intro iframe");
        if(video.length > 0){
            var videoW = video.width();
            video.height( videoW * 9 / 16 );
        }
       
    },
    talentTrips : function(){
        $('.talent-trips .m-trip').click(function(){
            btAppSchema.jumpToTrip($(this).data('tid'));
        });
    },
    wxEvents: function () {
        var appMessage = {
            title: shr_wechat_title_friend,
            desc: shr_wechat_summary_friend,
            link: location.href,
            imgUrl: shr_wechat_image
        };
        var timeLine = {
            title: shr_wechat_title_circle,
            desc: shr_wechat_summary_circle,
            link: location.href,
            imgUrl: shr_wechat_image
        };
        wx.ready(function(){
            wx.onMenuShareAppMessage(appMessage);
            wx.onMenuShareTimeline(timeLine);
        });
    },
    likeEvents: function () {
        // 旅行产品喜欢功能
        btAppSchema.changeBookmarkBtnState(BT.context('is_liked'));
        var marking = false;
        btAppSchema.toggleBookmark = function() {
            if(marking){
                return;
            }
            marking = true;
            var state = btAppSchema.currentBookmarkBtnState;
            btAppSchema.changeBookmarkBtnState(1 - state);
            $.ajax({
                url: '/liked/',
                type: 'post',
                data: {
                    csrfmiddlewaretoken: $("body").attr("data-csrf"),
                    operator: state == 0? "create": "delete",
                    type: 3,
                    id: BT.context('pk')
                },
                success:function(){
                    marking = false;
                },
                error : function(){
                    marking = false;
                }
            });
        };
    },
    topScroll: function () {
        // window.onscroll = function(){
        //     var _scrollTop = $('body').scrollTop();
        //     $('header').css({top: _scrollTop*0.3});
        // };
        document.addEventListener("touchmove", parallaxScroll, false);
        document.addEventListener("scroll", parallaxScroll, false);
        function parallaxScroll () {
            var _scrollTop = $('body').scrollTop();
            $('header').css({top: _scrollTop*0.3});
        }
        // $(window).swipeUp(parallaxScroll);
    },
    refreshExpriedCounting: function () {
        window.clearTimeout(Product.TIME);
        var $product_countdown = $('#product-countdown'),
            // p = $("#expiredCounting"),
            $order_now = $("#order-now"),
            time = $product_countdown.attr('data-time'),
            expired = new Date(parseInt(time, 10) * 1000), //抢购开始时间
            now = new Date(), delta = (expired - now) / 1000,
            minute = parseInt(delta / 60, 10) % 60,
            second = parseInt(delta % 60, 10) + "",
            hour = parseInt(delta / 3600, 10) % 24,
            day = parseInt(delta / (3600 * 24), 10),
            text = "距离抢购开始还剩：",
            time = '';

        if(!$product_countdown){
            return;
        }

        if(expired < now) {
            // 抢购开始
            $order_now.text('立即预订').removeClass('hide btn-disable' );
            $product_countdown.text("抢购正在进行中");
        }else{
            // 抢购倒计时
            $order_now.text('暂未开始').addClass('btn-disable').removeClass('hide');
            if(day > 30){
                // time = "大于30天";
                // p.parent().parent().hide();
                $product_countdown.parent().hide();
                return;
            }
            if(day){
                time += day + "天" + hour + "小时" + minute + "分钟" + second + "秒";
            } else if(hour){
                time += hour + "小时" + minute + "分钟" + second + "秒";
            } else if(minute){
                time += minute + "分钟" + second + "秒";
            } else if(second){
                time += second + "秒";
            }
            $product_countdown.html(text + '<span id="expiredCounting">' + time + '</span>');
            Product.TIME = setTimeout(function(){
                Product.refreshExpriedCounting();
            }, 250);
        }
        
    },
    countdownEvents: function () {
        $('#order-now').on('click', function (e) {
            var self = $(this);
            if (self.hasClass('btn-disable') || self.hasClass('push') ) return;
            self.addClass('push');
            

            if ($("#valid_user").val() == 'None'){
                btAppSchema.jumpToLogin(location.href);
            }
            e.preventDefault();
            var url = BT.context('SECKILL_DOMAIN') + 'product/' + BT.context('pk') +'/scramble/';
            $.ajax({
                url: url,
                type: 'POST',
                crossDomain: true,
                dataType: 'json',
                success: function (data) {
                    self.removeClass('push');
                    if ( data.error_code === 10001 ) {
                        // 没资格
                        alert(data.prompt);
                    }else if ( data.error_code === 10000 ){
                        // 活动未开始未开始
                        alert(data.prompt);
                    }else{
                        if ( $('#order-now').data('qualified') !== 1 ) {
                            alert('抢购成功！名额保留30分钟，请马上确认预定，否则视为自动放弃');
                        }
                        window.location.href = data.url;
                    }
                },
                error: function(){
                   self.removeClass('push');
                },
                xhrFields: {
                    withCredentials: true
                }
            });
        });
    },
    seckillEvents: function () {
        var $product_countdown = $('#product-countdown'),
            $order_now = $('#order-now');
        if ( $product_countdown.length > 0 ) {        
            var url = BT.context('SECKILL_DOMAIN') + 'product/' + BT.context('pk') +'/?t='+new Date().getTime();
            $.ajax({
                url: url,
                type: 'GET',
                dataType: 'jsonp',
                success: function (data) {
                    var start_time = data.ts_start_time,
                        server_time = data.ts_server_time,
                        local_time = (new Date().getTime())/1000,
                        delta_start_time = start_time - (server_time - local_time);

                    $product_countdown.attr('data-time', delta_start_time);
                    if ( data.qualified ) {
                        $order_now.text('立即预订').removeClass('btn-disable hide').data('qualified', 1);
                    }
                    // 秒杀结束
                    if( data.end === 1 && !data.qualified) {                      
                        $order_now.html('抢购结束').removeClass('hide').addClass('btn-disable');
                        $product_countdown.html('抢购已结束，'+ data.stock + '人抢到了该产品'); 
                        $('#product-tatol').remove();                       
                    }else{
                        $('.info').append('<span id="product-tatol">库存总量为：'+ data.stock + '</span>');
                        Product.refreshExpriedCounting(); 
                    }
                    Product.countdownEvents();
                }
            });
        }
    },
    folderInit: function () {
        $('#folder').on('click', 'dt', function(e) {
            e.preventDefault();
            var _self = $(this);
            _self.toggleClass('fold').next('dd').toggleClass('hide').toggleClass('show');
            if(_self.hasClass('fold')){
                var _top = _self.offset().top;
                if(!Product.flag) _top = _top - 60;
                Product.scrollTo(_top, 100);               
            } 
        });
        $('#folder').on('click', '.btn-fold', function(e) {
            e.preventDefault();
            var _self = $(this);
            Product.scrollTo($('#folder').offset().top, 100);
            _self.parent('dd').toggleClass('hide').toggleClass('show').prev('dt').toggleClass('fold');
        });
        $('#folder dt').not('.hide').last().addClass('last');
    },
    initSchedulesNav: function(){
        
        var nav = $('#schedules-nav');
        if(nav.length == 0){
            return;
        }
        var navList = nav.find('li'),
            navContent = $('.schedules'),
            contentBox = navContent.find('.schedules-main li'),
            contentBoxTopMap = {},
            isclicked = false;
        
        
        //点击滚动
        navList.on('click',function(e){
            isclicked = true;
            var index = $.inArray(this,navList.toArray()),
                top = contentBox.eq(index).offset().top-15;
            navList.filter('.cur').removeClass('cur');
            $(this).addClass('cur');
            Product.scrollTo(top-1, 100);
            isclicked = false;
        });
        function schedulesScrollNav () {
            var scrollTop = $(window).scrollTop(),
                navContentTop = navContent.offset().top,
                navContentHeight = navContent.height(),
                navHeight = nav.height();
            //吸顶

            if ( !navigator.userAgent.match(/(iPhone|iPod|iPad)/) ) {
                if( (scrollTop > navContentTop - 1) && (scrollTop < navContentTop + navContentHeight - navHeight - 1) ){
                    nav.addClass('schedules-nav-fixed');
                }else{
                    nav.removeClass('schedules-nav-fixed');
                }
            }
            if( isclicked ){
                return;
            }
            contentBox.each(function(index,item){
                contentBoxTopMap[index] = $(item).offset().top-52;
            });
            //tab选中状态
            for(var i=0;i<navList.length;i++){
                if(i == 0){
                    //页面位于第一个上方
                    if(scrollTop < contentBoxTopMap[0] && !navList.eq(0).hasClass('cur')){
                        navList.filter('.cur').removeClass('cur');
                        navList.eq(0).addClass('cur');
                        return;
                    }
                }else{
                    //页面位于两个模块之间
                    var beforeBoxHeight = contentBox.eq(i-1).height();
                    if(scrollTop > contentBoxTopMap[i-1] + beforeBoxHeight  && scrollTop < contentBoxTopMap[i] && !navList.eq(i).hasClass('cur')){
                        navList.filter('.cur').removeClass('cur');
                        navList.eq(i).addClass('cur');
                        return;
                    }
                }
            }
        }
        $(window).on('scroll', function() {
            schedulesScrollNav();
        });
    },
    relatedTripsInit: function () {
        var _tripContent = '';
        var _url = '/tp/'+ BT.context('pk') +'/related-trips/';
        $.ajax({
            url: _url,
            type: 'GET',
            dataType: 'json',
            success: function (data) {
                if (data.length > 0) {
                    _tripContent = Product.btp('related-trips-templates', {list: data});
                    $(_tripContent).appendTo('#related-trips ul');
                    $('#related-trips').prev('dt').removeClass('hide').addClass('last').siblings('dt').removeClass('last');
                }else{
                    $('#related-trips').prev('dt').addClass('hide');
                }
            }
        });
        var gotoTrip = function (e) {
            e.preventDefault();
            var _tripId = $(this).data('id');
            btAppSchema.jumpToTrip(_tripId);
        };
        $('#related-trips').on('click', 'a', gotoTrip);
    }
};

function warn(){
     $("#warn_area").show();
     $("#backWall").css({
             "opacity":0.5,
             "z-index":555,
     });
}

$(function(){
    // Appdownload
    if(BT && BT.Appdownload){
        BT.Appdownload.init();
    }
    // comment
    var comment = new BT.Comment({});
    comment.getComments();
    // Product Page Func

    // banner图
    if((!BT.context('has_video') && BT.context('banners') > 0) || (BT.context('isTalent') && BT.context('banners') > 0 )){
        Product.topSlider();
    }

    if(BT.context('isTalent')){
        //达人页面
        //Product.talentHeader();
        Product.talentVideo();
        Product.talentTrips();
    }else{
        Product.relatedTripsInit();
    }
    
    Product.seckillEvents();

    // Product.topScroll();
    Product.folderInit();
    Product.initSchedulesNav();
    Product.likeEvents();
    Product.wxEvents();

    var downloadbanner = $('.m-app-download .download-banner'),
        footerbanner = $('.affix');
    $('#comment-area').on('focus',function(e){
        if(downloadbanner.length > 0){
            downloadbanner.hide();
        }
        footerbanner.hide();
    }).on('blur',function(e){
        if(downloadbanner.length > 0){
            downloadbanner.show();
        }
        footerbanner.show();
    });

    $("#close_img1").click(function(){
        $("#warn_area").hide();
        $("#backWall").css({
           "opacity":0,
           "z-index":-1,
        });
    });
});
